package com.hz.api.admin.web.app;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.hz.api.admin.model.entity.ApiUsersEntity;
import com.hz.api.admin.model.request.SetScoreRequest;
import com.hz.api.admin.web.service.LOLService;
import com.hz.api.admin.web.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Controller
public class HomeController {

    @Resource
    private UserService userService;

    @Resource
    private LOLService lolService;

    @GetMapping("/web/login")
    public String login(Model model, HttpServletRequest request) {
        String token = getCookie(request);
        if(StringUtils.isBlank(token)){
            return "login";
        }
        JWT jwt = JWTUtil.parseToken(token);
        String userId = jwt.getPayload("userId").toString();
        ApiUsersEntity apiUsersEntity = userService.getUserInfoById(userId);
        if (ObjectUtils.isEmpty(apiUsersEntity)) {
            return "login";
        }
        return "redirect:/web/home";
    }

    @GetMapping("/web/home")
    public String home(Model model) {
        return "home";
    }

    @GetMapping("/web/welcome")
    public String welcome(Model model) {
        return "welcome";
    }

    @GetMapping("/web/center")
    public String center(Model model) {
        model.addAttribute("lolRankUsers", lolService.getLolRankUsers());
        return "center";
    }

    @GetMapping("/web/lol/score")
    public String score(Model model) {
        model.addAttribute("lolRankUsers", lolService.getLolRankUsers());
        return "score";
    }
    @GetMapping("/web/lol/record")
    public String record(Model model) {
      SetScoreRequest SetScoreRequest = null;
      model.addAttribute("lolRankUsers", lolService.getLolRankUsers());
      return "record";
    }


    public String getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String token = "";
        if (ObjectUtils.isNotEmpty(cookies)) {
            if (Objects.nonNull(cookies)) {
                for (Cookie cookie : cookies) {
                    if (cookie != null) {
                        if ("token".equals(cookie.getName())) {
                            token = cookie.getValue();
                        }
                    }
                }
            }
        }
        return token;
    }
}
